'use strict';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function getEach(dir){

    let files = fs.readdirSync(dir);
    let controllerFile = files.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
    })
    return controllerFile;
}

function readRequest(files){
    files.forEach((item) => {
        let tmpPath = path.join(__dirname,item);
        let route = require(tmpPath);
        for(let key in route){
            let type = route[key][0];
            let fn = route[key][1];
            if(type === 'get'){
                router.get(key,fn);
            }else if(type === 'post'){
                router.post(key,fn);
            }else{
                router.delete(key,fn);
            }
        }
    })
}

module.exports = function(currentDir){
    let dir = currentDir || __dirname;
    let controllerFile = getEach(dir);
    readRequest(controllerFile);
    return router.routes();
}